package com.honghu.villagepost.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.ada.common.util.CustomHelper;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.honghu.villagepost.MainActivity;
import com.honghu.villagepost.R;
import com.honghu.villagepost.api.ApiService;
import com.honghu.villagepost.base.BaseActivity;
import com.honghu.villagepost.callback.DialogCallback;
import com.honghu.villagepost.callback.LzyResponse;
import com.honghu.villagepost.constant.Constants;
import com.honghu.villagepost.entity.FileResult;
import com.honghu.villagepost.entity.ShopApplyDetail;
import com.honghu.villagepost.util.GlideUtil;
import com.honghu.villagepost.util.ImageUtil;
import com.honghu.villagepost.widget.PhotoPopup;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.impl.LoadingPopupView;
import com.lxj.xpopup.interfaces.SimpleCallback;
import com.lzy.okgo.model.Response;
import com.wuhenzhizao.sku.utils.ScreenUtils;

import org.devio.takephoto.app.TakePhotoActivity;
import org.devio.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ShopApplyActivity extends TakePhotoActivity implements View.OnClickListener {

    public static final int TYPE_CARD_FRONT = 0;
    public static final int TYPE_CARD_REVERSE = 1;
    private EditText mEtName;
    private EditText mEtCardNo;
    private EditText mEtPhone;
    private TextView mEtCardType;
    private ImageView mIvCardFront;
    private ImageView mIvCardReverse;
    private TextView mConfirmTv;
    private TextView mAuditSuccTv;
    private String mCardFrontPath;
    private String mCardRecersePath;

    private OptionsPickerView<String> mCardTypeChooseDialog;

    private int mTakePhotoType;

    private LoadingPopupView loadingPopup;

    private ShopApplyDetail mShopApplyDetail;

    public static void startActivity(Context context, ShopApplyDetail shopApplyDetail){
        Intent intent = new Intent(context, ShopApplyActivity.class);
        intent.putExtra(Constants.ITEM, shopApplyDetail);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(getLayoutId());

        init(savedInstanceState);

        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        if (intent != null){
            mShopApplyDetail = intent.getParcelableExtra(Constants.ITEM);
            if (mShopApplyDetail != null){
                mEtName.setText(mShopApplyDetail.name);
                mEtName.setSelection(mShopApplyDetail.name.length());

                mEtCardNo.setText(mShopApplyDetail.idCardNo);
                mEtCardNo.setSelection(mShopApplyDetail.idCardNo.length());

                mEtPhone.setText(mShopApplyDetail.mobile);
                mEtPhone.setSelection(mShopApplyDetail.mobile.length());

                mEtCardType.setText("身份证");

                mCardFrontPath = mShopApplyDetail.idCardPicFront;
                GlideUtil.loadNoneImg(mIvCardFront, mCardFrontPath);

                mCardRecersePath = mShopApplyDetail.idCardPicBack;
                GlideUtil.loadNoneImg(mIvCardReverse, mCardRecersePath);

                if (mShopApplyDetail.state == 1 || mShopApplyDetail.state == 6){
                    mConfirmTv.setText("修改");
                }else if (mShopApplyDetail.state == 3){
                    mConfirmTv.setVisibility(View.GONE);
                    mAuditSuccTv.setVisibility(View.VISIBLE);
                }
            }
        }
    }


    protected int getLayoutId() {
        return R.layout.activity_shop_apply;
    }

    protected void init(Bundle savedInstanceState) {
        Toolbar mToolbar = findViewById(R.id.common_toolbar);
        mToolbar.setNavigationIcon(R.mipmap.ic_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("填写资料");
        findViewById(R.id.tv_sub_title).setVisibility(View.GONE);
        mEtName = findViewById(R.id.et_name);
        mEtCardNo = findViewById(R.id.et_card_no);
        mEtPhone = findViewById(R.id.et_phone);
        mEtCardType = findViewById(R.id.et_card_type);
        mIvCardFront = findViewById(R.id.iv_card_front);
        mIvCardReverse = findViewById(R.id.iv_card_reverse);
        mConfirmTv = findViewById(R.id.confirm_tv);
        mAuditSuccTv = findViewById(R.id.tv_audit_succ);

        mEtCardType.setOnClickListener(this);
        mIvCardFront.setOnClickListener(this);
        mIvCardReverse.setOnClickListener(this);
        mConfirmTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.et_card_type){
            ScreenUtils.hideKeyboard(this);
            showChooseCardType();
        }else if (v.getId() == R.id.iv_card_front){
            ScreenUtils.hideKeyboard(this);
            choosePic(TYPE_CARD_FRONT);
        }else if (v.getId() == R.id.iv_card_reverse){
            ScreenUtils.hideKeyboard(this);
            choosePic(TYPE_CARD_REVERSE);
        }else if (v.getId() == R.id.confirm_tv){
            ScreenUtils.hideKeyboard(this);
            appyShop();
        }
    }

    private void appyShop() {
        String name = mEtName.getText().toString().trim();
        String cardNo = mEtCardNo.getText().toString().trim();
        String phone = mEtPhone.getText().toString().trim();
        String cardType = mEtCardType.getText().toString().trim();
        if (TextUtils.isEmpty(name)){
            ToastUtils.showShort("请输入真实姓名");
            return;
        }
        if (TextUtils.isEmpty(cardNo)){
            ToastUtils.showShort("请输入真实身份号");
            return;
        }
        if (TextUtils.isEmpty(phone)){
            ToastUtils.showShort("请输入联系方式");
            return;
        }

        if (TextUtils.isEmpty(cardType)){
            ToastUtils.showShort("请选择身份证类型");
            return;
        }

        if (TextUtils.isEmpty(mCardFrontPath)){
            ToastUtils.showShort("请选择身份证人面像");
            return;
        }

        if (TextUtils.isEmpty(mCardRecersePath)){
            ToastUtils.showShort("请选择身份证国徽面");
            return;
        }

        showLoadingDialog();
        if (mShopApplyDetail == null){
            ApiService.uploader(this, new File(mCardFrontPath), new DialogCallback<LzyResponse<FileResult>>() {
                @Override
                public void onSuccess(Response<LzyResponse<FileResult>> response) {
                    String frontPath = response.body().data.url;
                    ApiService.uploader(this, new File(mCardRecersePath), new DialogCallback<LzyResponse<FileResult>>() {
                        @Override
                        public void onSuccess(Response<LzyResponse<FileResult>> response) {
                            String reversePath = response.body().data.url;

                            appyShopReq(name, cardNo, phone, cardType, frontPath, reversePath);
                        }

                        @Override
                        public void onError(Response<LzyResponse<FileResult>> response) {
                            super.onError(response);
                            dismissLoadingDialog();
                        }
                    });
                }

                @Override
                public void onError(Response<LzyResponse<FileResult>> response) {
                    super.onError(response);
                    dismissLoadingDialog();
                }
            });
        }else {
            if (!ImageUtil.isHttpUrl(mCardFrontPath) && !ImageUtil.isHttpUrl(mCardRecersePath)){
                ApiService.uploader(this, new File(mCardFrontPath), new DialogCallback<LzyResponse<FileResult>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<FileResult>> response) {
                        String frontPath = response.body().data.url;
                        ApiService.uploader(this, new File(mCardRecersePath), new DialogCallback<LzyResponse<FileResult>>() {
                            @Override
                            public void onSuccess(Response<LzyResponse<FileResult>> response) {
                                String reversePath = response.body().data.url;

                                modifyAppyShopReq(name, cardNo, phone, cardType, frontPath, reversePath);
                            }

                            @Override
                            public void onError(Response<LzyResponse<FileResult>> response) {
                                super.onError(response);
                                dismissLoadingDialog();
                            }
                        });
                    }

                    @Override
                    public void onError(Response<LzyResponse<FileResult>> response) {
                        super.onError(response);
                        dismissLoadingDialog();
                    }
                });
            }else if (!ImageUtil.isHttpUrl(mCardFrontPath)){
                ApiService.uploader(this, new File(mCardFrontPath), new DialogCallback<LzyResponse<FileResult>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<FileResult>> response) {
                        String frontPath = response.body().data.url;
                        modifyAppyShopReq(name, cardNo, phone, cardType, frontPath, mCardRecersePath);
                    }

                    @Override
                    public void onError(Response<LzyResponse<FileResult>> response) {
                        super.onError(response);
                        dismissLoadingDialog();
                    }
                });
            }else if (!ImageUtil.isHttpUrl(mCardRecersePath)){
                ApiService.uploader(this, new File(mCardRecersePath), new DialogCallback<LzyResponse<FileResult>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<FileResult>> response) {
                        String reversePath = response.body().data.url;
                        modifyAppyShopReq(name, cardNo, phone, cardType, mCardFrontPath, reversePath);
                    }

                    @Override
                    public void onError(Response<LzyResponse<FileResult>> response) {
                        super.onError(response);
                        dismissLoadingDialog();
                    }
                });
            }
        }
    }

    private void appyShopReq(String name, String cardNo, String phone, String cardType, String frontPath, String reversePath) {
        ApiService.applyShop(this, name, cardNo, phone, frontPath, reversePath, new DialogCallback<LzyResponse<Object>>(this) {
            @Override
            public void onSuccess(Response<LzyResponse<Object>> response) {
                dismissLoadingDialog();
                ToastUtils.showShort("店铺申请提交成功");
                finish();
            }

            @Override
            public void onError(Response<LzyResponse<Object>> response) {
                super.onError(response);
                dismissLoadingDialog();
            }
        });
    }

    private void modifyAppyShopReq(String name, String cardNo, String phone, String cardType, String frontPath, String reversePath) {
        ApiService.modifyApplyShop(this, name, cardNo, phone, frontPath, reversePath, new DialogCallback<LzyResponse<Object>>(this) {
            @Override
            public void onSuccess(Response<LzyResponse<Object>> response) {
                dismissLoadingDialog();
                ToastUtils.showShort("店铺申请修改成功");
                finish();
            }

            @Override
            public void onError(Response<LzyResponse<Object>> response) {
                super.onError(response);
                dismissLoadingDialog();
            }
        });
    }

    private void showLoadingDialog(){
        if (loadingPopup == null){
            loadingPopup = (LoadingPopupView) new XPopup.Builder(this)
                    .asLoading("正在加载中");

        }
        loadingPopup.show();
    }

    private void dismissLoadingDialog(){
        if (loadingPopup != null && loadingPopup.isShow()) {
            loadingPopup.dismiss();
        }
    }

    /**
     * Desc:证件类型
     * <p>
     * Author: [李豫]
     * Date: 2021-05-15
     */
    private void showChooseCardType() {
        if (mCardTypeChooseDialog == null){
            List<String> cardType = new ArrayList<>();
            cardType.add("身份证");
            mCardTypeChooseDialog = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    mEtCardType.setText(cardType.get(options1));
                }
            })
                    .setTitleText("证件类型")
                    .setDividerColor(Color.BLACK)
                    .setCancelColor(getResources().getColor(R.color.colorAccent))
                    .setSubmitColor(getResources().getColor(R.color.colorAccent))
                    .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                    .setContentTextSize(18)
                    .build();
            mCardTypeChooseDialog.setPicker(cardType);
        }
        mCardTypeChooseDialog.show();
    }

    private BasePopupView mTakePhoto;
    private void choosePic(int type) {
        mTakePhotoType = type;
        mTakePhoto = new XPopup.Builder(this)
                .autoOpenSoftInput(true)
                .setPopupCallback(new SimpleCallback())
                .asCustom(new PhotoPopup(this, new PhotoPopup.Onclick() {
                    @Override
                    public void first() {
                        CustomHelper.TakePhoto(getTakePhoto(), CustomHelper.PICK_BY_TAKE, false);
                        mTakePhoto.dismiss();
                    }

                    @Override
                    public void second() {
                        CustomHelper.TakePhoto(getTakePhoto(), CustomHelper.PICK_BY_SELECT, false);
                        mTakePhoto.dismiss();
                    }
                }))
                .show();
    }

    @Override
    public void takeSuccess(TResult result) {
        super.takeSuccess(result);

        String compressPath = result.getImage().getCompressPath();
        if (mTakePhotoType == TYPE_CARD_FRONT){
            mCardFrontPath = compressPath;
            GlideUtil.loadNoneImg(mIvCardFront, compressPath);
        }else if (mTakePhotoType == TYPE_CARD_REVERSE){
            mCardRecersePath = compressPath;
            GlideUtil.loadNoneImg(mIvCardReverse, compressPath);
        }
    }
}